import json

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse

# Create your views here.
from django.views import View

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from shopping_mall import settings


class QQLoginURLView(View):

    def get(self, request):
        # 使用QQloginTool生成跳转链接
        # 初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state='xxx')
        # 获取QQ登录扫码页面,扫码后得到Authorization Code
        login_url = oauth.get_qq_url() # QQ登录页面网址
        # 返回响应
        return JsonResponse({'code': 0, 'login_url': login_url})

class OauthView(View):

    def get(self, request):
        # 获取code
        code = request.GET.get('code')
        print('code------', code)
        # 根据code获取token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state='xxx')
        access_token = oauth.get_access_token(code)
        print('access_token------', access_token)
        # 根据token获取openid
        openid = oauth.get_open_id(access_token)
        print('openid------', openid)
        # 根据openid去数据库查询OAuthQQUser账号数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print(e)
            # 如果不存在 捕获异常 走没有绑定的逻辑,去绑定页面
            # 前端分析后 返回openid key叫做access_token
            # 对openid加密
            openid = generate_access_token(openid)
            # print('openid--加密后:', openid)
            return JsonResponse({'code': 400, 'access_token': openid})
        else:
            # 如果存在 正常返回数据 做登录状态保持
            # session
            login(request, qquser.user)
            # cookie
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie("username", qquser.user.username)
            # 合并cookie购物车到redis
            response = merge_cart_cookie_to_redis(request, qquser.user, response)
            # 返回响应
            return response

    def post(self, request):
        # 接收请求
        body = request.body
        data_dict = json.loads(body)
        # 获取请求参数
        password = data_dict.get("password")
        mobile = data_dict.get("mobile")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")
        print('openid--', openid)
        # 解密获取原数据
        openid = check_access_token(openid)
        # 验证参数(忽略)

        # 根据手机号 查询是否注册
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            print(e)
            # 没有注册 创建一个user对象 绑定 用户和openid
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password)
        else:
            # 已经注册 密码验证 密码正确 直接绑定 用户和openid
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})

        try:
            # 绑定user和openid
            OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '账号已绑定,无法添加'})

        # 状态保持
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie("username", user.username)
        # 返回响应
        return response